<!--
 * @Author: 李金深 2896583081@qq.com
 * @Date: 2023-05-23 17:25:28
 * @LastEditors: 李金深 2896583081@qq.com
 * @LastEditTime: 2023-08-02 10:25:55
 * @FilePath: /com.huizhouyiren.web.d0101/src/views/index/index.vue
 * @Description: 主页
-->
<script setup>
import { ref, onMounted, watch, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUser } from '@/stores/user'
import { useSystem } from '@/stores/system'
import { useEmail } from '@/stores/email'
import { useChat } from '@/stores/chat'
import { NIcon } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import {
  PersonCircleOutline as UserIcon,
  Pencil as EditIcon,
  LogOutOutline as LogoutIcon,
  KeySharp as PasswordIcon
} from '@vicons/ionicons5'
import mitt from '@/mitt/index'
import useSystemNotify from '@/hooks/useSystemNotify'
import useInitData from '@/hooks/useInitData'
import browserNotify from './notify'

import CustomImage from '@/components/customImage/customImage.vue'
import PopupMessage from '@/components/popupMessage/popupMessage.vue'
import AudioControl from '@/components/audioControl/audioControl.vue'
// import {
//     useMessage
// } from "naive-ui";

// import icon1 from "../../assets/image/navbar/navbar1.png";
import icon2 from '../../assets/image/navbar/navbar2.png'
import icon8 from '../../assets/image/navbar/navbar8.png'
import icon4 from '../../assets/image/navbar/navbar4.png'
import icon5 from '../../assets/image/navbar/navbar5.png'
import icon6 from '../../assets/image/navbar/navbar6.png'
// import icon7 from "../../assets/image/navbar/navbar7.png";

const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const userStore = useUser()
const systemStore = useSystem()
const emailStore = useEmail()
const chatStore = useChat()

// 数据初始化
useInitData()
// 系统通知
useSystemNotify()

const getSystemData = () => {
  systemStore.getCountryList() // 获取国家列表
  systemStore.getMajorList() // 获取职位列表
  systemStore.getSite() // 获取系统信息
}

const navbarMenu = ref([
  {
    text: 'home',
    key: 'home',
    icon: icon6,
    url: '/main',
    patch: 'main'
  },
  // {
  //     text: "online",
  //     key: "online",
  //     icon: icon1,
  //     url: "/main/online"
  // }, {
  //     text: "search",
  //     key: "search",
  //     icon: icon7,
  //     url: "/main/search"
  // },
  {
    text: 'posts',
    key: 'posts',
    icon: icon5,
    url: '/main/post',
    patch: 'post'
  },
  {
    text: 'chat',
    key: 'chat',
    icon: icon2,
    url: '/chat',
    patch: 'chat',
    count: 0
  },
  {
    text: 'email',
    key: 'email',
    icon: icon8,
    url: '/email',
    patch: 'email',
    count: 0
  },
  {
    text: 'gift',
    key: 'gift',
    icon: icon4,
    url: '/main/mall',
    patch: 'mall'
  }
])
let show = ref(false)

function initNavbar() {
  navbarMenu.value.forEach((item) => {
    item.text ? (item.text = t(`navbar.${item.key}`)) : ''
  })
  options.value.forEach((item) => {
    item.label = t(`${item.key}`)
  })
}

// 路由监听
let patch = ref('')
watch(
  () => route.fullPath,
  (newVal) => {
    // console.log(route.meta)
    patch.value = route.meta.patch
    let token = localStorage.getItem('USER_TOKEN')
    if (newVal.includes('/login') || newVal == '/' || !token) {
      show.value = false
    } else {
      show.value = true
    }
  },
  {
    immediate: true,
    deep: true
  }
)
/**
 * @description: 路由跳转
 * @param {*} url
 * @return {*}
 */
function goPage(url) {
  router.push(url)
}

let localeFlag = ref(false)
let value = localStorage.getItem('localeFlag')
localeFlag.value = value && value == 'true' ? true : false

/**
 * @description: 语言修改
 * @param {*} flag
 * @return {*}
 */
const changeLanguage = () => {
  localeFlag.value = !localeFlag.value
  mitt.emit('changeLanguage', localeFlag.value + '')
  localStorage.setItem('localeFlag', localeFlag.value)
  initNavbar()
  getSystemData()
}

const renderIcon = (icon) => {
  return () => {
    return h(NIcon, null, {
      default: () => h(icon)
    })
  }
}
let options = ref([
  {
    label: '个人主页',
    key: 'navbar.homepage',
    icon: renderIcon(UserIcon)
  },
  {
    label: '编辑资料',
    key: 'navbar.edit',
    icon: renderIcon(EditIcon)
  },
  {
    label: '修改密码',
    key: 'setting.password',
    icon: renderIcon(PasswordIcon)
  },
  {
    label: '退出登录',
    key: 'navbar.logOut',
    icon: renderIcon(LogoutIcon)
  }
])

/**
 * @description: 点击下拉框触发的事件
 * @param {*} e
 * @return {*}
 */
function selectFunc(e) {
  switch (e) {
    case 'navbar.homepage':
      router.push('/main/homepage')
      break
    case 'navbar.edit':
      router.push('/main/profile')
      break
    case 'navbar.logOut':
      removeLocalData()
      mitt.emit('messageTip', {
        type: 'success',
        msg: 'msg.logoutSuccess',
        useTranslate: true
      })
      setTimeout(() => {
        router.push('/login')
      }, 1500)
      break
    case 'setting.password':
      router.push('/main/password')
      break
  }
}
/**
 * @description: 移除本地数据
 * @return {*}
 */
const removeLocalData = () => {
  localStorage.removeItem('USER_TOKEN')
  localStorage.removeItem('USER_INFO')
  localStorage.removeItem('chatUserInfo')
  chatStore.closeWebsocket()
  chatStore.$reset()
}

onMounted(() => {
  mitt.emit('changeLanguage', localeFlag.value + '')
  initNavbar()
})

let popupMsg = ref(null)
mitt.on('insufficientTip', () => {
  popupMsg.value.openModal()
})
/**
 * @description: 关闭弹窗
 * @return {*}
 */
const closePopup = function () {
  popupMsg.value.closeModal()
}

// 浏览器通知
browserNotify()

mitt.on('updateCount', (payload) => {
  let { type, count } = payload
  let index = navbarMenu.value.findIndex((item) => {
    return item.key == type
  })
  if (index > -1) {
    navbarMenu.value[index].count = count
  }
})
</script>
<template>
  <div class="bg-gray-100">
    <div class="fixed top-0 left-0 right-0 bg-themeBlue" style="height: 3.75rem; z-index: 100">
      <div class="relative flex items-center justify-center w-full h-full">
        <div style="" class="flex items-center justify-between h-full box_width">
          <div>
            <div
              v-if="systemStore.logo"
              style="width: 100px"
              class="flex items-center justify-center h-full overflow-hidden text-white"
            >
              <CustomImage
                bgColor="#2D57A1"
                :src="systemStore.logo"
                :customStyle="{
                  width: 'auto',
                  height: '50px'
                }"
              ></CustomImage>
            </div>
          </div>
          <div
            class="flex items-center justify-around h-full duration-500 sm:pr-28 xl:pr-0"
            style="flex: 1; max-width: 75%"
            v-if="show"
          >
            <div
              v-for="item in navbarMenu"
              :key="item.text"
              @click="goPage(item.url)"
              class="relative flex items-center justify-center h-full duration-500 cursor-pointer hover:bg-hoverBg"
              :style="{ width: (100 / 8) * 100 + '%' }"
              :class="patch == item.patch ? 'bg-hoverBg' : ''"
            >
              <div class="flex items-center">
                <div>
                  <div class="flex justify-center">
                    <img :src="item.icon" alt="" style="height: 1.125rem" />
                  </div>
                  <div class="mt-1 text-xs text-center text-white">{{ item.text }}</div>
                </div>
                <div
                  class="ml-1 text-xs font-bold text-white rounded-md bg-primary"
                  style="padding: 2px 4px"
                  v-if="item.count && item.count > 0"
                >
                  {{ item.count > 99 ? '99+' : item.count }}
                </div>
              </div>
              <div
                style="
                  height: 1.25rem;
                  width: 0.0625rem;
                  background-color: rgba(255, 255, 255, 0.3);
                "
                class="absolute right-0"
              ></div>
            </div>
            <div
              class="relative flex items-center justify-center h-full duration-500 cursor-pointer"
              :style="{ width: (100 / 8) * 100 + '%' }"
            >
              <div>
                <div class="bg-white rounded-full" @click="changeLanguage">
                  <img
                    src="../../assets/image/common/translators.png"
                    alt=""
                    style="
                      width: 1.875rem;
                      height: auto;
                      padding: 0.0625rem;
                      box-sizing: content-box;
                    "
                  />
                </div>
              </div>
              <div
                style="
                  height: 1.25rem;
                  width: 0.0625rem;
                  background-color: rgba(255, 255, 255, 0.3);
                "
                class="absolute right-0"
              ></div>
            </div>
          </div>
        </div>
        <div class="absolute top-0 bottom-0 right-4">
          <div class="flex items-center h-full" v-if="show">
            <div
              class="px-3 py-1 text-xs text-white border border-white border-solid rounded-full cursor-pointer"
              @click="goPage('/main/recharge')"
            >
              {{ $t('vip.topUp') }}
            </div>
            <n-dropdown :options="options" @select="selectFunc">
              <div
                style="width: 2.1875rem; height: 2.1875rem; overflow: hidden"
                class="ml-3 bg-white border-2 border-white border-solid rounded-full cursor-pointer"
              >
                <!-- <img src="../../assets/image/login/login2.png" alt=""> -->

                <img :src="userStore.userInfo.avatar" alt="" class="object-cover w-full h-full" />
              </div>
            </n-dropdown>
          </div>
          <div
            class="relative flex items-center justify-center h-full duration-500 cursor-pointer"
            v-if="!show"
          >
            <div>
              <div class="bg-white rounded-full" @click="changeLanguage">
                <img
                  src="../../assets/image/common/translators.png"
                  alt=""
                  style="width: 1.875rem; height: auto; padding: 0.0625rem; box-sizing: content-box"
                />
              </div>
            </div>
            <div
              style="height: 1.25rem; width: 0.0625rem; background-color: rgba(255, 255, 255, 0.3)"
              class="absolute right-0"
            ></div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="relative flex items-center justify-center w-full bg-themeBlue"
      style="height: 3.75rem"
    ></div>
  </div>
  <AudioControl></AudioControl>
  <PopupMessage
    ref="popupMsg"
    confirmText="system.topUpNow"
    @confirmFunc="goPage('/main/recharge')"
    @cancelFunc="closePopup"
  >
    <template #default>
      <div class="text-center">{{ emailStore.config.credit_tips }}</div>
    </template>
  </PopupMessage>
</template>
